package com.intelligentmeterreadingsys.waterlist.querywaterlist.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MKPlanNode;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.Overlay;
import com.baidu.mapapi.OverlayItem;

import com.baidu.mapapi.RouteOverlay;
import com.baidu.mapapi.TransitOverlay;
import com.intelligentmeterreadingsys.MapApplication;
import com.intelligentmeterreadingsys.R;

public class QueryRoutePlanMap extends MapActivity {
	// 定位图层
	public MyLocationOverlay mLocationOverlay = null;
	
	public String[] date = null;

	public MapView mMapView = null; // 地图View
	public MKSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用

	public String type = "公交";

	public LocationListener mLocationListener = null;// create时注册此listener，Destroy时需要Remove

	public MKPlanNode enNode = null;// 终点

	public MKPlanNode snNode = null;// 起点

	public Spinner spinner = null;

	public MKLocationManager locationMan = null;// 定位管理

	public static final int ITEM0 = Menu.FIRST;// 系统值

	public String locationtype = "gps";

	private final static int DIALOG = 1;
	public boolean isinit = true;
	
	public String adds="";

	@Override
	protected void onCreate(Bundle bundle) {

		super.onCreate(bundle);
		setContentView(R.layout.routeplan);
		enNode = new MKPlanNode();
		snNode = new MKPlanNode();
		mMapView = (MapView) findViewById(R.id.bmapView);

		// 初始化终点
		Intent intent = getIntent();
		if (intent.getDoubleExtra("latitude", 0.0) > 0.0) {

			GeoPoint point = new GeoPoint((int) (intent.getDoubleExtra(
					"latitude", 0.0) * 1E6), (int) (intent.getDoubleExtra(
					"longitude", 0.0) * 1E6));

			enNode.pt = point;
			adds=intent.getStringExtra("adds");
		} 
		init();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onPause() {
		MapApplication app = (MapApplication) this.getApplication();
		app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
		mLocationOverlay.disableMyLocation();

		app.mBMapMan.stop();
		super.onPause();
	}

	@Override
	protected void onResume() {
		MapApplication app = (MapApplication) this.getApplication();
		app.mBMapMan.getLocationManager().requestLocationUpdates(
				mLocationListener);
		app.mBMapMan.getLocationManager().setNotifyInternal(1, 10);
		mLocationOverlay.enableMyLocation();

		app.mBMapMan.start();
		super.onResume();
	}

	/**
	 * 初始化控件并设置参数
	 */
	public void init() {
		spinner = (Spinner) findViewById(R.id.mBtn_spinner);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				type = arg0.getItemAtPosition(arg2).toString();

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				type = "公交";

			}
		});
		MapApplication app = (MapApplication) this.getApplication();
		mLocationListener = new MyLocationListen();

		if (app.mBMapMan == null) {
			app.mBMapMan = new BMapManager(getApplication());
			app.mBMapMan.init(app.mStrKey,
					new MapApplication.MyGeneralListener());
		}
		app.mBMapMan.start();
		// 初始化地图Activity
		super.initMapActivity(app.mBMapMan);
		// 得到地图层的控制权，可以用它控制和驱动平移和缩放
		MapController bMapController = mMapView.getController();
		// 设置地图ZOOM级别
		bMapController.setZoom(17);
		mMapView.setBuiltInZoomControls(true);
		// 设置在缩放动画过程中也显示overlay,默认为不绘制
		mMapView.setDrawOverlayWhenZooming(true);

		// 添加定位图层
		mLocationOverlay = new MyLocationOverlay(this, mMapView);
		mMapView.getOverlays().add(mLocationOverlay);

		// 初始化搜索模块，注册事件监听
		mSearch = new MKSearch();
		locationMan = app.mBMapMan.getLocationManager();

		mSearch.init(app.mBMapMan, new MyMKSearchListen());

	}

	/**
	 * 收索模块监听器
	 * 
	 * @author king
	 * 
	 */
	public class MyMKSearchListen implements MKSearchListener {

		

		@Override
		public void onGetTransitRouteResult(MKTransitRouteResult res, int error) {
			System.out.println(error + "error");
			if (error != 0 || res == null) {
				Toast.makeText(QueryRoutePlanMap.this, "抱歉，未找到结果",
						Toast.LENGTH_SHORT).show();
				return;
			}
			TransitOverlay routeOverlay = new TransitOverlay(
					QueryRoutePlanMap.this, mMapView);
			// 此处仅展示一个方案作为示例
			routeOverlay.setData(res.getPlan(0));
			mMapView.getOverlays().clear();
			mMapView.getOverlays().add(routeOverlay);
			mMapView.getOverlays().add(new MyOverlay(enNode.pt,adds));
			mMapView.invalidate();
			mMapView.getController().animateTo(res.getStart().pt);
		}

		@Override
		public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
			

		}

		@Override
		public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) {
			System.out.println(error + "error");
			if (error != 0 || res == null) {
				Toast.makeText(QueryRoutePlanMap.this, "抱歉，未找到结果",
						Toast.LENGTH_SHORT).show();
				return;
			}
			RouteOverlay routeOverlay = new RouteOverlay(
					QueryRoutePlanMap.this, mMapView);
			routeOverlay.setData(res.getPlan(0).getRoute(0));
			mMapView.getOverlays().clear();
			mMapView.getOverlays().add(routeOverlay);
			mMapView.getOverlays().add(new MyOverlay(enNode.pt,adds));
			mMapView.invalidate();
			mMapView.getController().animateTo(res.getStart().pt);
		}

		@Override
		public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {

		}

		@Override
		public void onGetAddrResult(MKAddrInfo arg0, int arg1) {

		}

		@Override
		public void onGetRGCShareUrlResult(String arg0, int arg1) {
			
			
		}

		@Override
		public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) {

			System.out.println(error + "error");
			if (error != 0 || res == null) {
				Toast.makeText(QueryRoutePlanMap.this, "抱歉，未找到结果",
						Toast.LENGTH_SHORT).show();
				return;
			}
			RouteOverlay routeOverlay = new RouteOverlay(
					QueryRoutePlanMap.this, mMapView);
			// 此处仅展示一个方案作为示例
			routeOverlay.setData(res.getPlan(0).getRoute(0));			
			
			mMapView.getOverlays().clear();
			mMapView.getOverlays().add(routeOverlay);
			Drawable marker = getResources().getDrawable(R.drawable.a_key_to_upload); 
			//得到需要标在地图上的资源
		//	mMapView.getOverlays().add(new OverItemT(enNode.pt,marker, QueryRoutePlanMap.this)); 
			mMapView.getOverlays().add(new MyOverlay(enNode.pt,adds));
			mMapView.invalidate();
			mMapView.getController().animateTo(res.getStart().pt);

		
			
		}
	}

	/**
	 * 定位监听器
	 * 
	 * @author king
	 * 
	 */
	public class MyLocationListen implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
             if(location==null){
            	 return;
             }
			if (isinit) {
				
				GeoPoint pt = new GeoPoint(
						(int) (location.getLatitude() * 1E6),
						(int) (location.getLongitude() * 1E6));
				snNode.pt = pt;
				// 设置地图中心
               
				mMapView.getController().animateTo(pt);
				mMapView.invalidate();
				isinit = false;

			}
			// 用得到的经纬度构造一个GeoPoint
//			if (locationtype.equals("gps")) {
//				openGPSSettings();
//				if (location.getProvider().equals("gps")) {
//					initStroNode(location);
//				}
//			} 
			
				 initStroNode(location);
			
         
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
//		menu.add(0, ITEM0, 0, "定位优先级");

	//	menu.findItem(ITEM0 + 1);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == ITEM0) {
			showDialog(DIALOG + 1);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		Dialog dialog = null;
		switch (id) {

		case DIALOG + 1:
			if (locationtype.equals("gps")) {
				date = new String[] { "gps", "network" };
			} else {
				date = new String[] { "network", "gps" };
			}
			Builder builder = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder.setIcon(R.drawable.buttondraw);
			// 设置对话框的标题
			builder.setTitle("单选按钮对话框");
			// 0: 默认第一个单选按钮被选中

			builder.setSingleChoiceItems(date, 0,
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							locationtype = date[which];

						}
					});

			// 添加一个确定按钮
			builder.setPositiveButton(" 确 定 ",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							if (locationtype.equals("gps")) {
								
								locationInit();
							} else if (locationtype.equals("network")) {
							
								locationInit();
							}

						}
					});
			// 创建一个单选按钮对话框
			dialog = builder.create();
			break;
		}
		return dialog;
	}

	/**
	 * 定位初始化
	 */
	public void locationInit() {
		if (locationtype.equals("gps")) {
			locationMan.enableProvider(MKLocationManager.MK_GPS_PROVIDER);
			locationMan.disableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
		} else if (locationtype.equals("network")) {
			locationMan.enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
			locationMan.disableProvider(MKLocationManager.MK_GPS_PROVIDER);
		}

	}

	/**
	 * 得到起点
	 * 
	 * @param location
	 */
	public void initStroNode(Location location) {

		GeoPoint pt = new GeoPoint((int) (location.getLatitude() * 1E6),
				(int) (location.getLongitude() * 1E6));
		System.out.println(location.getLatitude()+"-------------");
		snNode.pt = pt;
		// 设置地图中心
	
		mMapView.getController().animateTo(pt);
		mMapView.invalidate();
		
		if (type.equals("公交")) {
			// 设置公交策略
			mSearch.setTransitPolicy(MKSearch.ECAR_TIME_FIRST);

			mSearch.transitSearch("重庆", snNode, enNode);

		} else if (type.equals("架车")) {
			// 设置架车测略
			mSearch.setDrivingPolicy(MKSearch.ECAR_DIS_FIRST);
			mSearch.drivingSearch("重庆", snNode, "重庆", enNode);
		} else if (type.equals("步行")) {			
			mSearch.walkingSearch("重庆", snNode, "重庆", enNode);			
		}

	}

	/**
	 * 自定义文本标注
	 * 
	 * @author king
	 * 
	 */
	public class MyOverlay extends Overlay {
		private String adds;
		private GeoPoint geoPoint;

		public MyOverlay(GeoPoint geoPoint,String adds) {
			this.adds=adds;
			this.geoPoint = geoPoint;
		}

		Paint paint = new Paint();

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {

			// 在天安门的位置绘制一个String
			Point point = mMapView.getProjection().toPixels(geoPoint, null);
			paint.setTextSize(17);
			paint.setAntiAlias(true);
			paint.setStrokeWidth(3);
			if(adds==null||adds.equals("")){
				adds="没有精确地址";
			}
			int k=adds.length()%8>0?adds.length()/8+1:adds.length()/8;
			
			if(k==1){
				paint.setColor(Color.BLUE);
				canvas.drawText(adds, point.x+30, point.y-30, paint);
			}else {
				for(int i=0;i<k;i++){
					String s="";
					if(adds.length()<=8){
						
						s=adds.substring(i*8, adds.length());
						
					}else{
						if(i==k-1){
							s=adds.substring(i*8, adds.length());
						}else{
							s=adds.substring(i*8, (i+1)*8);
						}												
					}
					paint.setColor(Color.BLUE);
					canvas.drawText(s, point.x+30, point.y-30-(k-i-1)*20, paint);
					
				}
			}
			
			paint.setColor(Color.BLACK);
			canvas.drawLine(point.x, point.y, point.x+20, point.y-40, paint);
			canvas.drawLine(point.x, point.y, point.x+20, point.y-20, paint);
			canvas.drawLine(point.x+20, point.y-20, point.x+180, point.y-20, paint);			
			canvas.drawLine(point.x+180, point.y-20, point.x+180, point.y-30-k*20, paint);
			canvas.drawLine( point.x+180, point.y-30-k*20, point.x+20,point.y-30-k*20 , paint);
			canvas.drawLine( point.x+20, point.y-40, point.x+20,point.y-30-k*20, paint);
		}

	}

	/**
	 * 点击事件标注
	 * @author king
	 *
	 */
	public class OverItemT extends ItemizedOverlay<OverlayItem> {

		private GeoPoint geopoint;
		private List<OverlayItem> GeoList = new ArrayList<OverlayItem>();
		private Context mContext;

		public OverItemT(GeoPoint geopoint, Drawable marker,Context context) {
			super(boundCenterBottom(marker));
			this.mContext=context;
			this.geopoint = geopoint;
			GeoList.add(new OverlayItem(geopoint, "p1", "这是标注"));
			populate();

		}

	

		@Override
		protected OverlayItem createItem(int arg0) {
			// TODO Auto-generated method stub
			return GeoList.get(0);
		}

		@Override
		public int size() {
			// TODO Auto-generated method stub
			return GeoList.size();
		}

		@Override
		// 处理当点击事件
		protected boolean onTap(int i) {
			Toast.makeText(this.mContext, GeoList.get(i).getSnippet(),
					Toast.LENGTH_SHORT).show();
			return true;
		}
	}
	
	/**
	 * 判断GPS是否存在或开启
	 */
	public boolean openGPSSettings() {
		LocationManager alm = (LocationManager) getSystemService(this.LOCATION_SERVICE);

		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

			return true;
		}
		Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
		startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
		return false;
	}
}
